<template>
  <div class="shop-fee-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      size="default"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="店铺" prop="shopIds">
            <el-select 
              v-model="formData.shopIds" 
              placeholder="请选择店铺" 
              style="width: 100%"
              multiple
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="3"
            >
              <el-option
                v-for="shop in shopList"
                :key="shop.id"
                :label="shop.shopName"
                :value="shop.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="费用类型" prop="feeType">
            <el-select 
              v-model="formData.feeType" 
              placeholder="请选择费用类型" 
              style="width: 100%"
              @change="handleFeeTypeChange"
            >
              <el-option label="物业费" value="PROPERTY" />
              <el-option label="水费" value="WATER" />
              <el-option label="电费" value="ELECTRIC" />
              <el-option label="燃气费" value="GAS" />
              <el-option label="卫生费" value="SANITATION" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 批量生成选项 -->
      <el-row :gutter="20" v-if="showBatchOptions">
        <el-col :span="24">
          <el-card shadow="never" class="batch-options-card">
            <template #header>
              <div class="batch-header">
                <el-icon><Calendar /></el-icon>
                <span>批量生成设置</span>
              </div>
            </template>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="生成月份" prop="batchMonth">
                  <el-date-picker
                    v-model="formData.batchMonth"
                    type="month"
                    placeholder="请选择生成月份"
                    style="width: 100%"
                    format="YYYY-MM"
                    value-format="YYYY-MM"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生成方式">
                  <el-radio-group v-model="formData.batchMode">
                    <el-radio value="STANDARD">按费用标准生成</el-radio>
                    <el-radio value="CUSTOM">自定义金额</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="formData.batchMode === 'CUSTOM'">
              <el-col :span="12">
                <el-form-item label="自定义金额" prop="customAmount">
                  <el-input-number
                    v-model="formData.customAmount"
                    placeholder="请输入费用金额"
                    :min="0"
                    :max="100000"
                    :precision="2"
                    style="width: 100%"
                  />
                  <template #suffix>元</template>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="24">
                <el-alert
                  :title="`将为 ${formData.shopIds?.length || 0} 个店铺生成 ${formData.feeTypeName || ''} 费用记录`"
                  type="info"
                  :closable="false"
                  show-icon
                />
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="!showBatchOptions">
        <el-col :span="12">
          <el-form-item label="费用金额" prop="feeAmount">
            <el-input-number
              v-model="formData.feeAmount"
              placeholder="请输入费用金额"
              :min="0"
              :max="100000"
              :precision="2"
              style="width: 100%"
            />
            <template #suffix>元</template>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="费用日期" prop="feeDate">
            <el-date-picker
              v-model="formData.feeDate"
              type="date"
              placeholder="请选择费用日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="到期日期" prop="dueDate">
            <el-date-picker
              v-model="formData.dueDate"
              type="date"
              placeholder="请选择到期日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付状态" prop="paymentStatus">
            <el-radio-group v-model="formData.paymentStatus">
              <el-radio :value="0">未支付</el-radio>
              <el-radio :value="1">已支付</el-radio>
              <el-radio :value="2">逾期</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="formData.paymentStatus === 1">
        <el-col :span="12">
          <el-form-item label="支付日期" prop="paymentDate">
            <el-date-picker
              v-model="formData.paymentDate"
              type="date"
              placeholder="请选择支付日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="formData.paymentMethod" placeholder="请选择支付方式" style="width: 100%">
              <el-option label="现金" value="CASH" />
              <el-option label="银行转账" value="BANK_TRANSFER" />
              <el-option label="支付宝" value="ALIPAY" />
              <el-option label="微信支付" value="WECHAT" />
              <el-option label="其他" value="OTHER" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="formData.paymentStatus === 1">
        <el-col :span="12">
          <el-form-item label="收据号" prop="receiptNumber">
            <el-input
              v-model="formData.receiptNumber"
              placeholder="请输入收据号"
              maxlength="50"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        {{ mode === 'add' ? '新增' : '保存' }}
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed, watch } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Calendar } from '@element-plus/icons-vue'
import { mockShopList, mockFeeRecordList } from '../mockData'
import { shopApi } from '@/api/shop'
import { shopFeeRecordApi } from '@/api/region/shop-fee-record'
import type { ShopFeeRecordVO, ShopVO } from '../types'

// Props
interface Props {
  feeId?: number | null
  mode: 'add' | 'edit'
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  success: []
  cancel: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const submitting = ref(false)
const shopList = ref<ShopVO[]>([])

// 表单数据
const formData = reactive({
  shopIds: [] as number[],
  feeType: '',
  feeTypeName: '',
  feeAmount: null as number | null,
  feeDate: '',
  dueDate: '',
  paymentStatus: 0,
  // 批量生成相关字段
  batchMode: 'STANDARD' as 'STANDARD' | 'CUSTOM',
  batchMonth: '',
  customAmount: null as number | null,
  paymentDate: '',
  paymentMethod: '',
  receiptNumber: '',
  remark: ''
})

// 表单验证规则
const formRules: FormRules = {
  shopIds: [
    { required: true, message: '请选择店铺', trigger: 'change' }
  ],
  feeType: [
    { required: true, message: '请选择费用类型', trigger: 'change' }
  ],
  feeAmount: [
    { required: true, message: '请输入费用金额', trigger: 'blur' }
  ],
  feeDate: [
    { required: true, message: '请选择费用日期', trigger: 'change' }
  ],
  dueDate: [
    { required: true, message: '请选择到期日期', trigger: 'change' }
  ],
  paymentStatus: [
    { required: true, message: '请选择支付状态', trigger: 'change' }
  ],
  paymentDate: [
    { required: true, message: '请选择支付日期', trigger: 'change' }
  ],
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ]
}

// 计算属性
const isEdit = computed(() => props.mode === 'edit')

// 是否显示批量生成选项
const showBatchOptions = computed(() => {
  return formData.shopIds.length > 1 && formData.feeType
})

// 费用类型名称映射
const feeTypeNameMap = {
  'PROPERTY': '物业费',
  'WATER': '水费',
  'ELECTRIC': '电费',
  'GAS': '燃气费',
  'SANITATION': '卫生费'
}

// 生命周期
onMounted(() => {
  loadShopList()
  if (isEdit.value && props.feeId) {
    loadFeeInfo()
  }
})

// 监听支付状态变化
watch(() => formData.paymentStatus, (newStatus) => {
  if (newStatus === 0) {
    formData.paymentDate = ''
    formData.paymentMethod = ''
    formData.receiptNumber = ''
  } else if (newStatus === 1) {
    formData.paymentDate = new Date().toISOString().split('T')[0]
  }
})

// 监听费用类型变化
watch(() => formData.feeType, (newType) => {
  formData.feeTypeName = feeTypeNameMap[newType as keyof typeof feeTypeNameMap] || ''
})

// 方法
const loadShopList = async () => {
  try {
    // 使用真实API获取店铺列表，遵循《Element Plus组件编码规范权威标准声明.md》规范
    const response = await shopApi.getShopPage({
      current: 1,
      size: 1000, // 获取所有店铺
      status: 1 // 只获取启用的店铺
    })
    
    if (response && response.code === 200 && response.data) {
      shopList.value = response.data.records || []
    } else {
      ElMessage.error(response?.message || '加载店铺列表失败')
      shopList.value = []
    }
  } catch (error) {
    ElMessage.error('加载店铺列表失败')
    console.error('加载店铺列表失败:', error)
    shopList.value = []
  }
}

// 费用类型变化处理
const handleFeeTypeChange = (value: string) => {
  formData.feeTypeName = feeTypeNameMap[value as keyof typeof feeTypeNameMap] || ''
}

const loadFeeInfo = async () => {
  if (!props.feeId) return
  
  try {
    const mockData = mockFeeRecordList()
    const fee = mockData.find(f => f.id === props.feeId)
    
    if (fee) {
      Object.assign(formData, {
        shopId: fee.shopId,
        feeType: fee.feeType,
        feeAmount: fee.feeAmount,
        feeDate: fee.feeDate,
        dueDate: fee.dueDate,
        paymentStatus: fee.paymentStatus,
        paymentDate: fee.paymentDate,
        paymentMethod: fee.paymentMethod,
        receiptNumber: fee.receiptNumber,
        remark: fee.remark
      })
    }
  } catch (error) {
    ElMessage.error('加载费用信息失败')
    console.error('加载费用信息失败:', error)
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    if (showBatchOptions.value) {
      // 批量生成费用记录
      await handleBatchGenerate()
    } else {
      // 单个费用记录
      await handleSingleSubmit()
    }
    
    ElMessage.success(isEdit.value ? '编辑成功' : '新增成功')
    emit('success')
  } catch (error) {
    if (error !== false) {
      ElMessage.error('提交失败')
      console.error('提交失败:', error)
    }
  } finally {
    submitting.value = false
  }
}

// 单个费用记录提交
const handleSingleSubmit = async () => {
  // TODO: 实现单个费用记录提交逻辑
  await new Promise(resolve => setTimeout(resolve, 1000))
}

// 批量生成费用记录
const handleBatchGenerate = async () => {
  try {
    // 构建批量生成请求数据
    const batchData = {
      shopIds: formData.shopIds,
      feeType: formData.feeType,
      batchMonth: formData.batchMonth,
      batchMode: formData.batchMode,
      customAmount: formData.customAmount,
      dueDate: formData.dueDate,
      paymentStatus: formData.paymentStatus,
      remark: formData.remark
    }
    
    // 调用后端批量生成API，遵循《Element Plus组件编码规范权威标准声明.md》规范
    const response = await shopFeeRecordApi.batchGenerate(batchData)
    
    if (response && response.code === 200 && response.data) {
      const result = response.data
      ElMessage.success(`成功为 ${result.successCount || formData.shopIds.length} 个店铺生成费用记录`)
    } else {
      ElMessage.error(response?.message || '批量生成失败')
    }
  } catch (error) {
    ElMessage.error('批量生成失败')
    console.error('批量生成失败:', error)
    throw error
  }
}

const handleCancel = () => {
  emit('cancel')
}
</script>

<style scoped>
.shop-fee-form {
  padding: 20px;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.form-actions .el-button {
  margin: 0 8px;
  min-width: 100px;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

.batch-options-card {
  margin: 20px 0;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
}

.batch-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #409eff;
}

.batch-header .el-icon {
  font-size: 16px;
}

:deep(.el-input__suffix) {
  color: #909399;
  font-size: 14px;
}
</style>
